package com.ferret.dao.specifications;

import com.ferret.bean.entity.ReadPic;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import javax.persistence.criteria.Predicate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Component
public class ReadPicSpecification {

    public static Specification<ReadPic> withAreaCodes(List<String> areaCodes) {
        return (root, query, criteriaBuilder) -> {
            if (areaCodes == null || areaCodes.isEmpty()) {
                return criteriaBuilder.conjunction();
            }

            List<Predicate> predicates = new ArrayList<>();
            for (String areaCode : areaCodes) {
                predicates.add(criteriaBuilder.like(root.get("djdw"), areaCode + "%"));
            }

            return criteriaBuilder.or(predicates.toArray(new Predicate[0]));
        };
    }

    public static Specification<ReadPic> withStatus(String status) {
        return (root, query, criteriaBuilder) -> {
            return criteriaBuilder.equal(root.get("ryzt"), status);
        };
    }

    /**
     * 按时间范围查询
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return Specification条件
     */
    public static Specification<ReadPic> withTimeRange(LocalDateTime startTime, LocalDateTime endTime) {
        return (root, query, criteriaBuilder) -> {
            // 如果开始时间和结束时间都为空，则不添加任何条件
            if (startTime == null && endTime == null) {
                return criteriaBuilder.conjunction();
            }
            if (startTime != null && endTime != null) {
                return criteriaBuilder.between(root.get("createTime"), startTime, endTime);
            } else if (startTime != null) {
                return criteriaBuilder.greaterThanOrEqualTo(root.get("createTime"), startTime);
            } else {
                return criteriaBuilder.lessThanOrEqualTo(root.get("createTime"), endTime);
            }
        };
    }
}
